package com.thinkinghead.mahjongrecorder;

import java.io.ByteArrayOutputStream;
import java.util.List;

import android.app.ActionBar;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.novoda.imageloader.core.util.DirectLoader;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.thinkinghead.mahjongrecorder.ui.dialog.DialogHelper;
import com.thinkinghead.mahjongrecorder.utils.TypeFaceManager;

public class EditUserActivity extends BasicActivity {
	private static String TAG = "EditUserActivity";
	// private ImageLoader imageLoader;
	private ImageView imageView;
	private Bitmap player_img;
	private Button btnUpdate;
	private EditText txtUsername, txtPassword;
	private TextView tvUsername, tvPassword;
	private ParseUser cUsr;

	// Pick image command
	private final int CHOOSE = 0;
	private final int CHOP = 1;
	private final int PREVIEW = 2;

	private Animation fadeInAnimation;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_user);
		cUsr = ParseUser.getCurrentUser();
		initView();
		initFontFace();
		fnInitListener();
		fnTitle();
	}

	private void fnTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle("Edit User");
	}

	private void fnInitListener() {
		imageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				fnLoadPhoto(v);
			}
		});
	}

	private void initView() {
		imageView = (ImageView) findViewById(R.id.player_img);
		tvUsername = (TextView) findViewById(R.id.tv_username);
		txtUsername = (EditText) findViewById(R.id.txt_username);
		tvPassword = (TextView) findViewById(R.id.tv_password);
		txtPassword = (EditText) findViewById(R.id.txt_password);
		btnUpdate = (Button) findViewById(R.id.btn_update);

		txtUsername.setText(cUsr.getUsername());
		txtPassword.setText(cUsr.getString("password"));
		ParseFile image = (ParseFile) cUsr.get("player_img");
		Log.d(TAG, "image:" + image);
		if (image != null) {
			String imgUrl = image.getUrl();
			Log.d(TAG, "imgUrl:" + imgUrl);
			// imageLoader = new ImageLoader(this);
			// imageLoader.DisplayImage(imgUrl, imageView);
			fnLoadImage(imgUrl);
		}
		Log.d(TAG, "pwd:" + cUsr.getString("password"));
		fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
	}

	private void fnLoadImage(final String imgUrl) {
		// ImageLoader imageLoader = ImageLoader.getInstance();
		// imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		// DisplayImageOptions options = new DisplayImageOptions.Builder()
		// .showStubImage(R.drawable.ic_launcher)
		// .cacheInMemory().cacheOnDisc().build();
		// imageLoader.displayImage(imgUrl, imageView, options);

		new Thread() {
			@Override
			public void run() {
				DirectLoader dl = new DirectLoader();
				Bitmap b = dl.download(imgUrl);
				setImageView(b);
			}
		}.start();
	}

	public void setImageView(final Bitmap bitmap) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				imageView.setImageBitmap(bitmap);
				imageView.startAnimation(fadeInAnimation);
			}
		});
	}

	private void initFontFace() {
		Typeface tf = TypeFaceManager.getTypeFace(getAssets());
		if (tf != null) {
			tvUsername.setTypeface(tf);
			txtUsername.setTypeface(tf);
			tvPassword.setTypeface(tf);
			txtPassword.setTypeface(tf);
			btnUpdate.setTypeface(tf);
		}
	}

	public void fnUpdate(View v) {
		String username = txtUsername.getText().toString();
		String password = txtPassword.getText().toString();
		if (username.equalsIgnoreCase("") || password.equalsIgnoreCase("")) {
			Toast.makeText(this,
					"Please enter a valid login name or password.",
					Toast.LENGTH_SHORT).show();
			return;
		}
		fnSaveUser(username, password);
	}

	private void fnSaveUser(String username, String password) {
		final EditUserActivity ctx = this;
		fnPreSave();

		cUsr.setUsername(username);
		cUsr.setPassword(password);
		if (player_img != null) {
			ByteArrayOutputStream blob = new ByteArrayOutputStream();
			player_img.compress(CompressFormat.PNG, 0, blob);
			byte[] imgArray = blob.toByteArray();

			ParseFile imgFile = new ParseFile("player_img.png", imgArray);
			cUsr.put("player_img", imgFile);
		}

		cUsr.saveInBackground(new SaveCallback() {

			@Override
			public void done(ParseException e) {
				fnPostSave();
				if (e == null) {
					Toast.makeText(getApplicationContext(),
							"User detail has been updated successfully.",
							Toast.LENGTH_LONG).show();
				} else {
					DialogHelper.getOkAlertDialog(ctx,
							"Error in connecting server..", e.getMessage())
							.show();
				}
			}
		});
	}

	private void fnPreSave() {
		DialogHelper.fnShowDialog(this);
	}

	private void fnPostSave() {
		DialogHelper.fnCloseDialog();
	}

	private void fnLoadPhoto(View v) {
		Intent i = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(Intent.createChooser(i, "Select Image"), CHOOSE);
	}

	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CHOOSE:
				Log.d(TAG, "CHOOSE");
				fnChop(intent, 16, 9, 200, 112);
				break;
			case CHOP:
				Log.d(TAG, "CHOP");
				fnPostChopImage(intent);
				break;
			case PREVIEW:
				break;
			}
		} else {

		}
	}

	private void fnChop(Intent i, int aspectX, int aspectY, int outputX,
			int outputY) {
		List<ResolveInfo> list = getPackageManager()
				.queryIntentActivities(i, 0);
		int size = list.size();
		if (size == 0) {
			Toast.makeText(this, "Can not find image crop app",
					Toast.LENGTH_SHORT).show();
			fnPostChopImage(i);
			return;
		} else {
			Uri imageUri = i.getData();
			if (imageUri != null) {
				Intent ic = new Intent("com.android.camera.action.CROP");
				// indicate image type and Uri
				ic.setDataAndType(imageUri, "image/*");
				// set crop properties
				ic.putExtra("crop", "true");

				if (aspectX > 0 && aspectY > 0) {
					// indicate aspect of desired crop, as ratio
					ic.putExtra("aspectX", aspectX);
					ic.putExtra("aspectY", aspectY);
				}

				if (outputX > 0 && outputY > 0) {
					// indicate output X and Y 100x 100y
					ic.putExtra("outputX", outputX);
					ic.putExtra("outputY", outputY);
				}

				// retrieve data on return
				ic.putExtra("return-data", true);
				// start the activity - we handle returning in onActivityResult
				// startActivityForResult(cropIntent, CHOP);
				try {
					startActivityForResult(
							Intent.createChooser(ic, "Chop Image"), CHOP);
				} catch (Exception e) {
				}
			} else {
				Toast.makeText(this, "Please choose an Image...",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	private void fnPostChopImage(Intent i) {
		Bundle extras = i.getExtras();
		player_img = extras.getParcelable("data");
		imageView.setImageBitmap(player_img);
	}

}
